from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.dao.kq_user_dao import Kq_userDao
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.kq_user_vo import Kq_userPageQueryModel, Kq_userModel, DeleteKq_userModel

from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class Kq_userService:
    """
    考勤用户花名册模块服务层
    """

    @classmethod
    async def get_kq_user_list_services(
        cls, query_db: AsyncSession, query_object: Kq_userPageQueryModel, is_page: bool = False
    ):
        """
        获取考勤用户花名册列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 考勤用户花名册列表信息对象
        """
        kq_user_list_result = await Kq_userDao.get_kq_user_list(query_db, query_object, is_page)

        return kq_user_list_result


    @classmethod
    async def add_kq_user_services(cls, query_db: AsyncSession, page_object: Kq_userModel):
        """
        新增考勤用户花名册信息service

        :param query_db: orm对象
        :param page_object: 新增考勤用户花名册对象
        :return: 新增考勤用户花名册校验结果
        """
        try:
            await Kq_userDao.add_kq_user_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_kq_user_services(cls, query_db: AsyncSession, page_object: Kq_userModel):
        """
        编辑考勤用户花名册信息service

        :param query_db: orm对象
        :param page_object: 编辑考勤用户花名册对象
        :return: 编辑考勤用户花名册校验结果
        """
        edit_kq_user = page_object.model_dump(exclude_unset=True, exclude={'del_flag', 'create_by', 'create_time', })
        kq_user_info = await cls.kq_user_detail_services(query_db, page_object.id)
        if kq_user_info.id:
            try:
                await Kq_userDao.edit_kq_user_dao(query_db, edit_kq_user)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='考勤用户花名册不存在')

    @classmethod
    async def delete_kq_user_services(cls, query_db: AsyncSession, page_object: DeleteKq_userModel):
        """
        删除考勤用户花名册信息service

        :param query_db: orm对象
        :param page_object: 删除考勤用户花名册对象
        :return: 删除考勤用户花名册校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await Kq_userDao.delete_kq_user_dao(query_db, Kq_userModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入序号为空')

    @classmethod
    async def kq_user_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取考勤用户花名册详细信息service

        :param query_db: orm对象
        :param id: 序号
        :return: 序号对应的信息
        """
        kq_user = await Kq_userDao.get_kq_user_detail_by_id(query_db, id=id)
        if kq_user:
            result = Kq_userModel(**CamelCaseUtil.transform_result(kq_user))
        else:
            result = Kq_userModel(**dict())

        return result

    @staticmethod
    async def export_kq_user_list_services(kq_user_list: List):
        """
        导出考勤用户花名册信息service

        :param kq_user_list: 考勤用户花名册信息列表
        :return: 考勤用户花名册信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '序号',
            'userId': '用户编号',
            'userName': '用户姓名',
            'phoneNumber': '联系电话',
            'department': '所属部门',
            'personId': '身份证号码',
            'employmentDate': '入职时间',
            # 'delFlag': '删除标志',
            # 'createBy': '创建者',
            # 'createTime': '创建时间',
            # 'updateBy': '更新者',
            # 'updateTime': '更新时间',
            # 'remark': '备注',
        }
        binary_data = ExcelUtil.export_list2excel(kq_user_list, mapping_dict)

        return binary_data
